<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { showFailToast, showLoadingToast, closeToast } from 'vant'
import useUserStore from '@/stores/modules/user'
import icon1 from '@/assets/icons/31.png'
import icon2 from '@/assets/icons/32.png'
import icon3 from '@/assets/icons/33.png'
import icon4 from '@/assets/icons/34.png'
import icon5 from '@/assets/icons/35.png'
import icon6 from '@/assets/icons/36.png'
import icon7 from '@/assets/icons/37.png'
import icon8 from '@/assets/icons/38.png'
import icon9 from '@/assets/icons/39.png'
import icon10 from '@/assets/icons/40.png'
import icon11 from '@/assets/icons/pxb.png'
import { getSessionStorageItem, getWeChatJsApiLink, isWeChat } from '@/utils/common'
import {
  getUserAccount,
  queryUserByMayKey,
  queryUserByMobile,
  getWechatJsapi,
  bindWeChat,
} from '@/api/jdb'

const router = useRouter()
const userStore = useUserStore()
const queryUserData = ref({
  nkDistributionUser: {
    name: undefined,
    phone: undefined,
  },
  schoolNkDistributionUser: {
    name: undefined,
    phone: undefined,
  },
})

const showQueryUserResultDialog = ref(false)
const studentMobile = ref('')
const showQueryUserDialog = ref(false)
const allMoney = ref(0)
const tixianmoney = ref(0)
const noTixianMoney = ref(0)
const yaoqingnumber = ref(0)
const vipnumber = ref(0)
const gridItemList = computed(() => [
  {title: '邀请下载', icon: icon1, show: true, action: 3, url: '/student-register' },
  // {title: '邀请购买VIP', icon: icon2, show: true, action: 3, url: '/vip' },
  // {title: '邀请购买VIP', icon: icon2, show: true, action: 1, url: import.meta.env.VITE_APP_OLD_JKJL_FX + '/jkjlfx/api/gongzhonghao/jkjlvip?mastrKey=' + userStore.userId },
  {title: '我的二维码', icon: icon3, show: true, action: 3, url: '/qr-code' },
  {title: '邀请推广人', icon: icon4, show: userStore.grade < 3, action: 3, url: '/invite-next-level' },
  {title: '推广人业绩', icon: icon5, show: userStore.grade < 3, action: 3, url: '/team' },
  {title: '关注公众号', icon: icon6, show: true, action: 3, url: '/we-chat-service-account' },
  {title: '扫码查询绑定分销人', icon: icon7, show: userStore.grade < 2, action: 2, url: 'scanQRCode'},
  {title: '根据学员手机号查询分销人', icon: icon8, show: userStore.grade < 2, action: 2, url: 'queryUser'},
  // {title: '招生素材', icon: icon9, show: true, action: 3, url: '/recruitment-material' },
  // {title: '每日海报', icon: icon10, show: true, action: 3, url: '/daily-poster' },
  // {title: '培训班', icon: icon11, show: true, action: 2, url: 'jumpJkjl' },
])

const canShowGridItemList = computed(() => {
  return gridItemList.value.filter(o => o.show)
})

const scanQRCode = () => {
  wx.scanQRCode({
    desc: 'scanQRCode desc',
    needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
    scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
    success: function(res) {
      console.log("调用扫描成功", res)
      var result = res.resultStr // 当needResult 为 1 时，扫码返回的结果
      console.log("扫码结果为：" + result)
      let resultArr = result.split('maykey=')
      if (!!resultArr[1] && resultArr[1].length > 0) {
        console.log("分销人员码为：" + resultArr[1])
        queryUserByMayKey({
          maykey: resultArr[1]
        }).then(response => {
          // console.log(response, 'response')
          queryUserData.value = response.data
          showQueryUserResultDialog.value = true
          showQueryUserDialog.value = false
        })
        return
      }
      showFailToast('分销人员码错误')
    },
    error: function(res) {
      console.log(res)
    }
  })
}
const getSignature = () => {
  // let url = window.location.href.split('#')[0]
  // // let url = router.currentRoute.value.fullPath.split('#')[0]
  // getWechatJsapi({
  //   url: url
  getWechatJsapi({
    url: getWeChatJsApiLink()
  }).then(response => {
    // console.log(response, 'response')
    let debug = false
    if (import.meta.env.VITE_ENV === 'development') {
      debug = true
    }
    wx.config({
      debug: debug, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
      appId: import.meta.env.VITE_WE_CHAT_APP_ID, // 必填，公众号的唯一标识
      timestamp: response.data.timestamp, // 必填，生成签名的时间戳
      nonceStr: response.data.nonceStr, // 必填，生成签名的随机串
      signature: response.data.signature, // 必填，签名，见附录1
      jsApiList: ['checkJsApi', 'scanQRCode']
      // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
    })
  })
}

const queryUser = () => {
  showQueryUserDialog.value = true
}
const jumpJkjl = () => {
  window.location.href = 'https://jkjl.jiakaopx.com/mobile/school?phone=' + userStore.phone
}
const go = (item) => {
  if (item.action === 1 ) {
    window.location.href = item.url
    return
  }
  if (item.action === 2) {
    if (item.url === 'scanQRCode') {
      scanQRCode()
    }
    if (item.url === 'queryUser') {
      queryUser()
    }
    if (item.url === 'jumpJkjl') {
      jumpJkjl()
    }
  }
  if (item.action === 3) {
    router.push(item.url)
  }
}
const logout = () => {
  userStore.logout().then(response => {
    router.replace('/login')
  })
}
const withdraw = () => {
  router.push('/withdraw')
}
const queryUserDialogBeforeClose = (action) => {
  if (action === 'confirm') {
    return queryUserByMobile({
      mobile: studentMobile.value
    }).then(response => {
      queryUserData.value = response.data
      showQueryUserResultDialog.value = true
      showQueryUserDialog.value = false
    })
  }
  return true
}

const initUserInfo = async () => {
  if (isWeChat()) {
    getSignature()
  }

  const toast = showLoadingToast({
    message: '正在加载 ...',
    forbidClick: true,
    duration: 0
  })

  const userAccountResponse = await getUserAccount()
  tixianmoney.value = userAccountResponse.data.tixianMoney
  noTixianMoney.value = userAccountResponse.data.noTixianMoney
  yaoqingnumber.value = userAccountResponse.data.inviteNumber
  vipnumber.value = userAccountResponse.data.vipNumber
  allMoney.value = userAccountResponse.data.allMoney

  closeToast()

  let openId = getSessionStorageItem("openId")
  if (!!openId) {
    if (userAccountResponse.data.type === 0) {
      //未绑定自动绑定
      await bindWeChat({openId})
    } else {
      //已绑定后不做其他操作
      // //绑定后换微信登录
      // if (openId !== userStore.openId) {
      //   await bindWeChat({openId})
      // }
    }
  }
}
initUserInfo()
</script>

<template>
  <div class="index-container">
    <div class="summary-container">
      <div class="withdraw-btn" @click="withdraw">提现</div>
      <div class="status-bar">
        <div>{{userStore.phone}}&nbsp;&nbsp;&nbsp;<span @click="logout">退出登录</span></div>
        <div>累计收益(元)：{{allMoney}}</div>
      </div>
      <div class="withdraw-desc">可提现金额（元）</div>
      <div class="withdraw-amount">{{noTixianMoney}}</div>
      <div class="invite-summary-container">
        <div class="invite-summary-left">
          <div>邀请下载成功</div>
          <div>{{yaoqingnumber}} 人</div>
        </div>
        <div class="invite-summary-separator"></div>
        <div class="invite-summary-right">
          <div>邀请学员购买VIP</div>
          <div>{{vipnumber}} 人</div>
        </div>
      </div>
    </div>
    <div class="navigation-container">
      <van-grid :column-num="3" :gutter="5" center clickable class="navigation-grid">
        <van-grid-item v-for="(item, index) in canShowGridItemList" @click="go(item)">
          <van-image width="25" height="25" :src="item.icon"></van-image>
          <div class="navigation-title">{{item.title}}</div>
        </van-grid-item>
      </van-grid>
    </div>
  </div>
  <van-dialog
      v-model:show="showQueryUserDialog"
      title="请输入学员手机号"
      show-cancel-button
      :before-close="queryUserDialogBeforeClose"
  >
    <van-cell-group>
      <van-field v-model="studentMobile"></van-field>
    </van-cell-group>
  </van-dialog>
  <van-dialog v-model:show="showQueryUserResultDialog" title="分销人信息">
    <van-cell-group>
      <van-cell title="分销人" :value="queryUserData.nkDistributionUser.name" />
    </van-cell-group>
  </van-dialog>
</template>

<style scoped>
.index-container {
  min-height: 100vh;
  background: #f2f2f2;
}
.navigation-grid {
  padding-top:5px;padding-bottom:5px
}
.navigation-title {
  margin-top:15px;width:100%;text-align: center;font-size:13px;
}
.summary-container{
  background-image: url(../assets/images/beijing.png);
  background-repeat: no-repeat;
  background-size: 100% 100%;
  color: white;
  position: relative;
}
.withdraw-btn {
  position: absolute;
  right: 35px;
  top: 95px;
  font-size: 14px;
}
.status-bar {
  display: flex;
  width: 98%;
  margin: 0 auto;
  justify-content: space-between;
  align-items: center;
  font-size: 13px;
  padding-top: 15px;
}
.withdraw-desc {
  font-size:13px;
  width:100%;
  text-align: center;
  margin-top:40px;
}
.withdraw-amount {
  font-size:32px;
  width:100%;
  text-align: center;
  margin-top:25px;
  margin-bottom:60px
}

.invite-summary-container {
  position: relative;
  display: flex;
  align-items: center;
  width: 100%;
}

.invite-summary-left,
.invite-summary-right {
  font-size:14px;
  text-align: center;
  flex: 1;
  box-sizing: border-box;
  padding: 10px;
  min-height:125px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

.invite-summary-left > div,
.invite-summary-right > div {
  margin-bottom:10px;
}

.invite-summary-separator {
  position: absolute;
  left: 50%;
  top: 10%;
  height: 80%;
  width: 1px;
  background-color: white;
  transform: translateX(-50%);
}

.invite-summary-left {
  background-image: url(../assets/images/beijing.png);
  background-repeat: no-repeat;
  background-size: 100% 100%;
}
.invite-summary-right {
  background-image: url(../assets/images/beijing2.png);
  background-repeat: no-repeat;
  background-size: 100% 100%;
}
</style>
